<template>
  <div class="modal modal-blur fade" id="relationModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">关系管理</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="table-responsive">
            <table class="table table-vcenter card-table">
              <thead>
                <tr>
                  <th><input class="form-check-input m-0 align-middle" type="checkbox" v-model="isAllChecked"
                           @change="handleToggleAll"></th>
                  <th class="w-1">关系ID</th>
                  <th class="w-1">机器ID</th>
                  <th>IP</th>
                  <th>标签</th>
                  <th>备注</th>
                  <th>状态</th>
                  <th>关联状态</th>
                  <th>最后修改时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in tableData" 
                    :key="index"
                    @click="toggleRow(item)"
                    :class="{'selected-row': item.checked}">
                  <td><input class="form-check-input m-0 align-middle" type="checkbox" v-model="item.checked"></td>
                  <td><span class="text-secondary">{{ item.refId }}</span></td>
                  <td><span class="text-secondary">{{ item.id }}</span></td>
                  <td>{{ item.ip }}</td>
                  <td>{{ item.label }}</td>
                  <td>{{ item.remark }}</td>
                  <td>
                    <span :class="{
                      'badge': true,
                      'bg-green-lt': item.status === 1,
                      'bg-red-lt': item.status === 0
                    }">
                      {{ item.status === 1 ? '启用' : '禁用' }}
                    </span>
                  </td>
                  <td>
                    <span :class="{
                      'badge': true,
                      'bg-blue-lt': item.refId,
                      'bg-gray-lt': !item.refId
                    }">
                      {{ item.refId ? '已关联' : '未关联' }}
                    </span>
                  </td>
                  <td>{{ item.lastUpdateTime }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" @click="saveChanges">绑定关系</button>
          <button type="button" class="btn btn-danger" @click="deleteRelations">解绑关系</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <ComponentModal
    :title="'信息'"
    :message="'操作成功'"
    :cancelText="'取消'"
    :confirmText="'确定'"
    ref="componentModalOutRef"
  />
</template>

<script setup>
import { ref, watch } from 'vue';
import { Modal } from 'bootstrap';
import ComponentModal from "@/components/ComponentModal.vue";

const props = defineProps({
  sourceMachineId: {
    type: String,
    required: true
  },
  sourceMachineLabel: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['save-success']);

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const modal = ref(null);
const tableData = ref([]);
const isAllChecked = ref(false);
const componentModalOutRef = ref(null);

// 初始化模态框
const initModal = () => {
  modal.value = new Modal(document.getElementById('relationModal'));
};

// 显示模态框
const show = async () => {
  await fetchData();
  modal.value.show();
};

// 隐藏模态框
const hide = () => {
  modal.value.hide();
};

// 获取数据
const fetchData = async () => {
  try {
    const params = new URLSearchParams({
      sourceMachineId: props.sourceMachineId,
      relationType: props.sourceMachineLabel || '',
      onlyRef: false
    });
    const response = await fetch(`${apiBaseUrl}/resident/machine-ref/searchPyVmMachines?${params.toString()}`);
    const data = await response.json();
    if (data.success) {
      tableData.value = data.result.map(item => ({
        ...item,
        checked: false
      }));
    }
  } catch (error) {
    console.error('Error fetching machine data:', error);
  }
};

// 处理全选/全不选
const handleToggleAll = () => {
  tableData.value.forEach(item => {
    item.checked = isAllChecked.value;
  });
};

// 切换行选中状态
const toggleRow = (item) => {
  item.checked = !item.checked;
};

// 保存更改
const saveChanges = async () => {
  // 获取选中的机器ID
  const selectedIds = tableData.value
    .filter(item => item.checked)
    .map(item => item.id);

  // 构建批量添加的请求数据
  const machineRefs = selectedIds.map(targetMachineId => ({
    sourceMachineId: props.sourceMachineId,
    targetMachineId: targetMachineId,
    relationType: props.sourceMachineLabel || '',
    remark: '主从关系'
  }));

  try {
    const response = await fetch(`${apiBaseUrl}/resident/machine-ref/batch-add`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(machineRefs)
    });
    
    const data = await response.json();
    if (data.success) {
      hide();
      emit('save-success');
    } else {
      showErrorToast(data.errorMsg || '未知错误');
    }
  } catch (error) {
    console.error('Error saving relations:', error);
    showErrorToast('保存失败，请稍后重试');
  }
};

// 删除关系
const deleteRelations = async () => {
  // 获取选中的机器ID
  const selectedIds = tableData.value
    .filter(item => item.checked && item.refId)
    .map(item => item.refId);

  if (selectedIds.length === 0) {
    componentModalOutRef.value.openWarnModal('请选择要解绑的关系');
    return;
  }

  try {
    const response = await fetch(`${apiBaseUrl}/resident/machine-ref/delete?ids=${selectedIds.join(',')}`, {
      method: 'DELETE'
    });
    
    const data = await response.json();
    if (data.success) {
      hide();
      componentModalOutRef.value.openInfoModal('解绑成功！');
      emit('save-success');
    } else {
      showErrorToast(data.errorMsg || '未知错误');
    }
  } catch (error) {
    console.error('Error deleting relations:', error);
    showErrorToast('解绑失败，请稍后重试');
  }
};

// 显示错误提示
const showErrorToast = (message) => {
  const toast = document.createElement('div');
  toast.className = 'toast toast-error';
  toast.innerHTML = `
    <div class="toast-header">
      <span class="toast-icon">!</span>
      <span class="toast-title">操作失败</span>
      <button type="button" class="btn-close" onclick="this.parentElement.parentElement.remove()"></button>
    </div>
    <div class="toast-body">
      ${message}
    </div>
  `;
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 3000);
};

// 监听表格数据变化，更新全选状态
watch(tableData, () => {
  isAllChecked.value = tableData.value.length > 0 && tableData.value.every(item => item.checked);
}, { deep: true });

// 暴露方法给父组件
defineExpose({
  show,
  hide,
  initModal
});
</script>

<style scoped>
/* 表格列宽优化 */
.table th:nth-child(1) { width: 40px; }   /* 复选框列 */
.table th:nth-child(2) { width: 80px; }   /* 关系ID列 */
.table th:nth-child(3) { width: 80px; }   /* 机器ID列 */
.table th:nth-child(4) { width: 150px; }  /* IP列 */
.table th:nth-child(5) { width: 120px; }  /* 标签列 */
.table th:nth-child(6) { width: 200px; }  /* 备注列 */
.table th:nth-child(7) { width: 100px; }   /* 状态列 */
.table th:nth-child(8) { width: 100px; }   /* 关联状态列 */
.table th:nth-child(9) { width: 180px; }  /* 最后修改时间列 */

/* 添加选中行的样式 */
.selected-row {
  background-color: rgba(32, 107, 196, 0.1) !important;
}

tr {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

tr:hover {
  background-color: rgba(32, 107, 196, 0.05);
}

/* 防止点击复选框时触发行点击事件 */
tr input[type="checkbox"] {
  cursor: pointer;
  pointer-events: auto;
}

/* Toast 样式 */
.toast {
  position: fixed;
  top: 1rem;
  right: 1rem;
  z-index: 9999;
  min-width: 300px;
  background: white;
  border-radius: 0.5rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
}

.toast-error {
  border-left: 4px solid #d63939;
}

.toast-header {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid rgba(98, 105, 118, 0.16);
}

.toast-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  margin-right: 0.5rem;
  background-color: #d63939;
  color: white;
  border-radius: 50%;
  font-weight: bold;
}

.toast-title {
  font-weight: 500;
  color: #1e293b;
  flex-grow: 1;
}

.toast-body {
  padding: 1rem;
  color: #475569;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.bg-green-lt {
  background-color: rgba(40, 167, 69, 0.15) !important;
  color: #2fb344 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-red-lt {
  background-color: rgba(220, 53, 69, 0.15) !important;
  color: #d63939 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-blue-lt {
  background-color: rgba(32, 107, 196, 0.15) !important;
  color: #206bc4 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-gray-lt {
  background-color: rgba(108, 117, 125, 0.15) !important;
  color: #6c757d !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}
</style> 